# -*- coding: utf-8 -*-
# @Time    : 2019/10/3 20:28
# @Author  : LiHaowen
# @Email   : lihaowen2017@163.com
# @File    : routing.py
from django.urls import path
from channels.auth import AuthMiddlewareStack  # 认证中间件栈
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator  # 允许的哪些ip能够访问
from web_ask.messager.consumers import MessagesConsumer
from web_ask.notifications.consumers import NotificationsConsumer
# self.scope["type"] 获取协议类型
# self.scope["url_route"]["kwargs"]["username"]获取url中关键字参数
# channels routing是scope级别的，一个连接只能由一个consumer接受和处理
application = ProtocolTypeRouter({
    # "http": views,
    # 普通的HTTP请求不需要我们手动在这里添加，框架会自动加载
    "websocket": AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter([
                    # 路由解析从上至下查找匹配；由于notifications，满足<str:username>筛选器，则导致
                    # 前端notifications url会匹配到第一个MessagesConsumer中去
                    # Django中导入三方包顺序问题也是由此引发，路由匹配规则
                    # 假定有用户username为notifications则无法进行私聊，出现bug；解决方案，1，不让用户注册此类用户名，
                    # 2 修改路由比如ws/u/<str:username>/
                    # path("ws/<str:username>/", MessagesConsumer),
                    # path("ws/notifications/", NotificationsConsumer),
                    path("ws/notifications/", NotificationsConsumer),
                    path("ws/<str:username>/", MessagesConsumer),

                ])
        )
    )
})

"""
均可以防止通过websocket进行csrf攻击
from channels.security.websocket import AllowedHostsOriginValidator  读取设置文件
from channels.security.websocket import OriginValidator 手动设置
application = ProtocolTypeRouter({
    "websocket": OriginValidator(
        AuthMiddlewareStack(
            URLRouter([
                    path("ws/<str:username>/", MessagesConsumer)
                ])
        ), [".imooc.com", "http://127.0.0.1:8000"]
    )
})

# AuthMiddlewareStack用于WebSocket认证，集成了CookieMiddleware，SessionMiddleware，
# AuthMiddleware, 兼容Django认证系统
"""

